package cn.itcast.jms;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;


// TODO NIU
@Component("mailListner")
public class MailListener implements MessageListener {

	//@Resource(name="mailSender")
	@Autowired
	private JavaMailSenderImpl  mailSender;
	
	public void onMessage(Message message) {
		

		MapMessage mailMessage = (MapMessage) message;
			
			
			
				try {
					MimeMessage msg = mailSender.createMimeMessage();
					MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
					helper.setFrom(mailSender.getUsername());
					helper.setTo(mailMessage.getString("mail"));
					helper.setSubject(mailMessage.getString("total"));
					// 第二个参数true，表示text的内容为html
					//<img/>标签，src='cid:file'，'cid'是contentId的缩写，'file'是一个标记，需要在后面的代码中调用MimeMessageHelper的addInline方法替代成文件
					helper.setText(
						"<!DOCTYPE html><html><body>"+mailMessage.getString("total")+"</body></html>"+mailMessage.getString("content"), true);
					//helper.addInline("file", file);
					mailSender.send(msg);
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
	
		
	}

}